<template>
  <el-dialog v-model="dialogVisible" width="832px" append-to-body>
    <Title :title="dialogTitle" />
    <div class="dialog-container">
      <el-form :model="form"  label-width="auto" ref="formRef" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="nickName" required>
              <el-input size="large" v-model="form.nickName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="学号" prop="stuId" required>
            <el-input size="large" v-model="form.stuId" placeholder="请输入学号" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="学院" prop="deptId" required>
            <el-select size="large" v-model="form.deptId" placeholder="请选择学院" clearable filterable style="width: 100%" @change="onDeptChange">
              <el-option v-for="opt in deptOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年级" prop="gradeId" required>
            <el-select size="large" v-model="form.gradeId" placeholder="请选择年级" clearable filterable style="width: 100%" :disabled="!form.deptId" @change="onGradeChange">
              <el-option v-for="item in gradeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="专业" prop="majorId" required>
            <el-select size="large" v-model="form.majorId" placeholder="请选择专业" clearable filterable style="width: 100%" :disabled="!form.gradeId">
              <el-option v-for="opt in majorOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input size="large" v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="简介" prop="summary">
        <el-input size="large" type="textarea" v-model="form.summary" placeholder="请输入简介" />
      </el-form-item>
    </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel" class="defauleButton">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { addStudent, updateStudent, getStudent } from '@/api/student'
import Title from '@/components/Title/index.vue'
import { ref, computed, getCurrentInstance } from 'vue'
import { listMajor } from '@/api/major'
const { proxy } = getCurrentInstance()

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const props = defineProps({
  tree: {
    type: Array,
    default: () => []
  }
})
const emit = defineEmits(['update'])
const deptOptions = computed(() => props.tree.map((item) => ({ value: item.deptId, label: item.deptName })))

// 年级选项：只显示选中学院下的年级
const gradeOptions = computed(() => {
  if (!form.value.deptId) return []
  const dept = props.tree.find((item) => item.deptId === form.value.deptId)
  return dept ? dept.children.map((grade) => ({ value: grade.gradeId, label: grade.gradeName })) : []
})

// 专业选项：只显示选中年级下的专业
const majorOptions = computed(() => {
  if (!form.value.gradeId) return []
  const dept = props.tree.find((item) => item.deptId === form.value.deptId)
  if (!dept) return []
  const grade = dept.children.find((g) => g.gradeId === form.value.gradeId)
  return grade ? grade.children.map((major) => ({ value: major.majorId, label: major.majorName })) : []
})

const onDeptChange = (val) => {
  form.value.gradeId = ''
  form.value.majorId = ''
}
const onGradeChange = (val) => {
  form.value.majorId = ''
}

const form = ref({
  nickName: '',
  stuId: '',
  deptId: '', // 新增：用于学院必填校验
  email: '',
  summary: '',
  gradeId: '',
  majorId: '',
  updateBy: '',
  updateTime: '',
  remark: '',
  status: '',
  password: ''
})

const rules = ref({
  nickName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  stuId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择学院', trigger: 'change' }],
  gradeId: [{ required: true, message: '请选择年级', trigger: 'change' }],
  majorId: [{ required: true, message: '请选择专业', trigger: 'change' }]
})
const cancel = () => close()
const confirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.value.studentId) {
        // 修改学生信息
        updateStudent(form.value).then(() => {
          proxy.$modal.msgSuccess('操作成功')
          emit('update')
          close()
        })
      } else {
        // 新增学生：默认赋予学生角色
        const payload = { ...form.value, roleIds: [5] }
        addStudent(payload).then(() => {
          proxy.$modal.msgSuccess('操作成功')
          emit('update')
          close()
        })
      }
    }
  })
}
const close = () => (dialogVisible.value = false)
const reset = () => {
  form.value = {
    nickName: '',
    stuId: '',
    deptId: '', // 新增：保持reset时也有该字段
    email: '',
    summary: '',
    gradeId: '',
    majorId: '',
    updateBy: '',
    updateTime: '',
    remark: '',
    status: '',
    password: ''
  }
  proxy.resetForm('formRef')
}
const init = (id) => {
  reset()
  dialogTitle.value = id ? '修改学生信息' : '新增学生信息'
  id && getDetail(id)
  dialogVisible.value = true
}
const getDetail = (id) => {
  getStudent(id).then((res) => {
    form.value = res.data
    // 确保状态为字符串以正确回显下拉选项
    form.value.status = res.data.status !== undefined && res.data.status !== null ? String(res.data.status) : ''
  })
}
const openDialog = (id = null) => {
  init(id)
}
defineExpose({ openDialog })
</script>
